import type { IStack, IStructureObj } from "../types";

export default class Stack<T> implements IStack<T> {
  private items: IStructureObj<T>;
  private count: number;

  constructor() {
    this.items = {};
    this.count = 0;
  }

  push(item: T): void {
    this.items[this.count] = item;
    this.count++;
  }
  pop(): T | undefined {
    if (this.isEmpty()) return void 0;
    this.count--;
    const result = this.items[this.count];
    delete this.items[this.count];
    return result;
  }
  peek(): T | undefined {
    if (this.isEmpty()) return void 0;
    return this.items[this.count - 1];
  }
  isEmpty(): boolean {
    return this.count === 0;
  }
  size(): number {
    return this.count;
  }
  clear(): void {
    this.items = {};
    this.count = 0;
  }
  toString(): string {
    if (this.isEmpty()) {
      return "";
    }
    let result = `${this.items[0]}`;
    for (let i = 1; i < this.count; i++) {
      result += `,${this.items[i]}`;
    }
    return result;
  }
}
